<template>
  <div class="clearFix">
    <div id="mapAmap2" class="clearFix card-shadow">
      <div class="clearFix">
        <canvas></canvas>
      </div>
    </div>
    <div id="panel0"></div>
  </div>
</template>

<script>
  import AMap from 'AMap'
  import AMapUI from 'AMapUI'
  import * as Utils from '@/utils/index'
  export default {
    name: '',
    props: [],
    components: { },
    data() {
      return {
        imgUrl_car_red: require('@/assets/car/car_red.png'),
        imgUrl_car_green: require('@/assets/car/car_green.png'),
        imgUrl_car_yellow: require('@/assets/car/car_yellow.png'),
        chartsData: []
      }
    },
    mounted() {
      // this.getList()
    },
    methods: {
      initCharts(data, toChartsParams) {
        const { queryType, areaType, provinceCodeList } = toChartsParams
        // type  - 全国（看省）-省（看市）-市（看区）-区（看车辆列表）/-车队（看车辆列表）-单个车（看车）
        console.log('oneSelectCharts-initCharts', 'queryType:', queryType, 'areaType:', areaType, 'provinceCodeList', provinceCodeList)
        const toProvinceCodeList = provinceCodeList
        // const toProvinceCodeList = [130000, 610000, 340000]
        const toData = data
        // const toData = [
        //   { longitude: 116.663843, latitude: 40.203412, type: '20', plateLicenseNo: '赣B20922' },
        //   { longitude: 116.523843, latitude: 39.703412, type: '20', plateLicenseNo: '赣A20222' },
        //   { longitude: 116.413843, latitude: 39.993412, type: '10', plateLicenseNo: '赣A50922' },
        //   { longitude: 113.953843, latitude: 22.723412, type: '30', plateLicenseNo: '赣H44422' },
        //   { longitude: 113.952874, latitude: 22.863861, type: '10', plateLicenseNo: '赣A33922' }
        // ]
        const _this = this
        const zoom = _this.changeZoom(areaType)
        // typeOneFunc() 高德标注点行政聚合api 需要的是 经纬度集合
        const new_data = []
        toData.map(item => {
          new_data.push(item.longitude + ',' + item.latitude)
        })
        console.log('oneSelectCharts-zoom', zoom)
        if (queryType === '') {
          // 全国- 各省 车辆统计 数字聚合 分布
          this.typeOneFunc(new_data, zoom, queryType, toProvinceCodeList)
        } else if (queryType === 'province') {
          // 省 - 单省 车辆统计 数字聚合 分布
          this.typeSixFunc(new_data, zoom, queryType, provinceCodeList)
        } else if (queryType === 'city') {
          // 市- 区 车辆统计 数字聚合 分布
          this.typeSixFunc(new_data, zoom, queryType, provinceCodeList)
        } else if (queryType === 'county') {
          // 区- 全部车辆状态 单标注 分布
          this.typeThreeFunc(toData, zoom, queryType)
        }  else if (queryType === 'plateLicenseNo') {
          // 车- 单个车辆 单标注 分布2
          this.typeThreeFunc(toData, zoom, queryType)
        } else if (queryType === 'fleetName') {
          // 车队- 全部车辆状态 单标注 分布
          this.typeThreeFunc(data, zoom, queryType)
        }
      },
      changeZoom(areaType) {
        let zoom = 12
        if (areaType === 'province') {
          zoom = 6
        } else if (areaType === 'city') {
          zoom = 9
        } else if (areaType === 'county') {
          zoom = 11
        } else {
          zoom = 3
        }
        console.log('changeZoom()-zoom', zoom)
        return zoom
      },
      typeOneFunc(data, zoom, queryType, provinceCodeList) {
        const _this = this
        console.log('typeOneFunc()')
        // const { lng, lat } = params
        // 创建地图
        const mapObj = new AMap.Map('mapAmap2', {
          // center: [lng, lat],
          // mapStyle: 'amap://styles/grey',
          zoom: zoom
        })
        // console.log('mapObj', mapObj)
        function initPage(DistrictCluster, $) {
          const distCluster = new DistrictCluster({
            map: mapObj, // 所属的地图实例
            zIndex: 11,
            topAdcodes: provinceCodeList, // 设置将显示的 省 值为 省份的code集合
            getPosition: function(item) {
              // console.log('initPage()-getPosition()-item', item)
              if (!item) {
                return null
              }
              const parts = item.split(',')
              // 返回经纬度
              return [parseFloat(parts[0]), parseFloat(parts[1])]
            },
            renderOptions: {
              featureEventSupport: true, // 区划面是否开启事件支持，默认true
              featureClickToShowSub: true, // 点击区划面是否触发进入子级区划，默认false
              // 基础样式
              featureStyle: {
                fillStyle: '#8b84dd', // 填充色
                lineWidth: 1, // 描边线宽
                strokeStyle: '#3e5464', // 描边色
                // 鼠标Hover后的样式
                hoverOptions: {
                  fillStyle: 'rgba(255,255,255,0.2)'
                }
              },
              // 特定区划级别的默认样式
              featureStyleByLevel: {
                // 全国
                country: {
                  fillStyle: 'red'
                },
                // 省
                province: {
                  fillStyle: 'rgba(116, 196, 118, 0.7)'
                },
                // 市
                city: {
                  fillStyle: 'rgba(161, 217, 155, 0.6)'
                },
                // 区县
                district: {
                  fillStyle: 'rgba(199, 233, 192, 0.5)'
                }
              },
              // 直接定义某写区划面的样式
              getFeatureStyle: function(feature, dataItems) {
                // console.log('getFeatureStyle()-feature', feature, 'dataItems', dataItems)
                if (dataItems.length === 0) {
                  return {
                    fillStyle: '#D7D7D7'
                  }
                } else if (dataItems.length > 1000) {
                  return {
                    fillStyle: 'orange'
                  }
                } else {
                  return {
                    fillStyle: '#eee'
                  }
                }
              }
            }
          })
          // 监听地图- 区划面 的点击事件
          const clickDistClusterHandler = function(e, feature) {
            // log.success("carMarker模拟触发了地图click事件!");
            console.log('DistCluster-province 模拟触发了地图click事件-e', e.type, feature.properties)
            const properties = feature.properties
            // 向父级调用事件
            _this.$emit('map-area-click', properties)
          }
          window.distCluster = distCluster
          distCluster.on('featureClick', clickDistClusterHandler)
          const now_data = data
          // const now_data = ['114.259712,22.717237', '113.982478,22.674277', '113.886884,22.785418', '115.979406,39.99281']
          distCluster.setData(now_data)
        }
        // 加载相关组件
        AMapUI.load(['ui/geo/DistrictCluster', 'lib/$'], function(DistrictCluster, $) {
          // 启动页面
          initPage(DistrictCluster, $)
        })
      },
      typeSixFunc(data, zoom, queryType, provinceCodeList) {
        const _this = this
        console.log('typeOneFunc()')
        // const { lng, lat } = params
        // 创建地图
        const mapObj = new AMap.Map('mapAmap2', {
          // center: [lng, lat],
          // mapStyle: 'amap://styles/grey',
          zoom: zoom
        })
        // console.log('mapObj', mapObj)
        function initPage(DistrictCluster, $) {
          const distCluster = new DistrictCluster({
            map: mapObj, // 所属的地图实例
            zIndex: 11,
            // topAdcodes: [], // 设置将显示的 省 值为 省份的code集合
            topAdcodes: provinceCodeList, // 设置将显示的 省 值为 省份的code集合
            getPosition: function(item) {
              // console.log('initPage()-getPosition()-item', item)
              if (!item) {
                return null
              }
              const parts = item.split(',')
              // 返回经纬度
              return [parseFloat(parts[0]), parseFloat(parts[1])]
            },
            renderOptions: {
              featureEventSupport: true, // 区划面是否开启事件支持，默认true
              featureClickToShowSub: true, // 点击区划面是否触发进入子级区划，默认false
              // 基础样式
              featureStyle: {
                fillStyle: '#8b84dd', // 填充色
                lineWidth: 1, // 描边线宽
                strokeStyle: '#3e5464', // 描边色
                // 鼠标Hover后的样式
                hoverOptions: {
                  fillStyle: 'rgba(255,255,255,0.2)'
                }
              },
              // 特定区划级别的默认样式
              featureStyleByLevel: {
                // 全国
                country: {
                  fillStyle: 'rgba(49, 163, 84, 0.8)'
                },
                // 省
                province: {
                  fillStyle: 'rgba(116, 196, 118, 0.7)'
                },
                // 市
                city: {
                  fillStyle: 'rgba(161, 217, 155, 0.6)'
                },
                // 区县
                district: {
                  fillStyle: 'rgba(199, 233, 192, 0.5)'
                }
              },
              // 直接定义某写区划面的样式
              getFeatureStyle: function(feature, dataItems) {
                // console.log('getFeatureStyle()-feature', feature, 'dataItems', dataItems)
                if (dataItems.length === 0) {
                  return {
                    fillStyle: '#D7D7D7'
                  }
                } else if (dataItems.length > 1000) {
                  return {
                    fillStyle: 'orange'
                  }
                } else {
                  return {
                    fillStyle: '#eee'
                  }
                }
              }
            }
          })
          // 监听地图- 区划面 的点击事件
          const clickDistClusterHandler = function(e, feature) {
            // log.success("carMarker模拟触发了地图click事件!");
            console.log('DistCluster-province 模拟触发了地图click事件-e', e.type, feature.properties)
            const properties = feature.properties
            // 向父级调用事件
            _this.$emit('map-area-click', properties)
          }
          window.distCluster = distCluster
          distCluster.on('featureClick', clickDistClusterHandler)
          const now_data = data
          // const now_data = ['114.259712,22.717237', '113.982478,22.674277', '113.886884,22.785418', '115.979406,39.99281']
          distCluster.setData(now_data)
        }
        // 加载相关组件
        AMapUI.load(['ui/geo/DistrictCluster', 'lib/$'], function(DistrictCluster, $) {
          // 启动页面
          initPage(DistrictCluster, $)
        })
      },
      typeFiveFunc(data, zoom, queryType) {
        const _this = this
        console.log('typeOneFunc()', 'zoom', zoom)
        const capitals = data
        const mapObj = new AMap.Map('mapAmap2', {
          // center: new AMap.LngLat(capitals[0].longitude, capitals[0].latitude),
          zoom: zoom
        })
        mapObj.clearMap() // 清除地图覆盖物
        const setFitViewArr1 = createMarker(capitals)
        console.log('setFitViewArr1', setFitViewArr1.length)
        // mapObj.setFitView(setFitViewArr1) // 调整视野达到最佳显示区域
        // 途径节点 marker 集合
        function createMarker(now_arr) {
          const middleMarkers = []
          for (let f = 0; f < now_arr.length; f++) {
            const item = now_arr[f]
            // driverIcon 类别
            let color = ''
            if (item.type === '30') {
              color = '#DC143C'
            } else if (item.type === '10') {
              color = '#008000'
            } else if (item.type === '20') {
              color = '#FFD700'
            } else {
              color = '#008000'
            }
            const carMarker = new AMap.CircleMarker({
              map: mapObj,
              center: new AMap.LngLat(item.longitude, item.latitude),
              fillColor: color,
              fillOpacity: 1,
              // strokeColor: '#000',
              strokeOpacity: 1,
              cursor: 'pointer',
              radius: 20,
              zIndex: 10,
              bubble: true
            })
            // 给 Text 带上自定义私货
            carMarker.lisaCarInfo = item
            const now_item = item
            now_item.queryType = queryType
            // 监听地图- Text 的 点击事件
            const clickHandler1 = function(e) {
              // log.success("carText模拟触发了地图click事件!");
              console.log('carText模拟触发了地图click事件-e')
              const carInfo = e.target.lisaCarInfo
              new AMap.InfoWindow({
                content: '车架号:' + carInfo.vin + '</br>车牌号:' + carInfo.plateLicenseNo
              }).open(mapObj, e.lnglat)
              // 向父级调用事件
              _this.$emit('car-click', now_item)
            }
            carMarker.on('click', clickHandler1)
            carMarker.setMap(mapObj)
            middleMarkers.push(carMarker)
          }
          return middleMarkers
        }
      },
      typeTwoFunc(data, zoom, queryType) {
        const _this = this
        console.log('typeTwoFunc()', 'zoom', zoom)
        const capitals = data
        const mapObj = new AMap.Map('mapAmap2', {
          center: new AMap.LngLat(capitals[0].longitude, capitals[0].latitude),
          zoom: zoom
        })
        mapObj.clearMap() // 清除地图覆盖物
        for (let f = 0; f < capitals.length; f++) {
          const item = capitals[f]
          // driverIcon 类别
          let color = ''
          if (item.type === '30') {
            color = '#DC143C'
          } else if (item.type === '10') {
            color = '#008000'
          } else if (item.type === '20') {
            color = '#FFD700'
          } else {
            color = '#008000'
          }
          const carMarker = new AMap.CircleMarker({
            map: mapObj,
            center: new AMap.LngLat(item.longitude, item.latitude),
            fillColor: color,
            fillOpacity: 1,
            // strokeColor: '#000',
            strokeOpacity: 1,
            cursor: 'pointer',
            radius: 16,
            zIndex: 10,
            bubble: true
          })
          // 给 Text 带上自定义私货
          carMarker.lisaCarInfo = item
          const now_item = item
          now_item.queryType = queryType
          // 监听地图- Text 的 点击事件
          const clickHandler0 = function(e) {
            // log.success("carText模拟触发了地图click事件!");
            console.log('carText模拟触发了地图click事件-e')
            const carInfo = e.target.lisaCarInfo
            const now_text = _this.createTextDome(carInfo)
            new AMap.InfoWindow({
              content: now_text
            }).open(mapObj, e.lnglat)
            // 向父级调用事件
            _this.$emit('car-click', now_item)
          }
          carMarker.on('click', clickHandler0)
          carMarker.setMap(mapObj)
          // -------------分割线----------------
          // 创建 text
          const carText = new AMap.Text({
            position: new AMap.LngLat(item.longitude, item.latitude),
            offset: new AMap.Pixel(56, 0),
            text: item.plateLicenseNo,
            map: mapObj
          })
          // 给 Text 带上自定义私货
          carText.lisaCarInfo = item
          // 监听地图- Text 的 点击事件
          const clickHandler2 = function(e) {
            // log.success("carText模拟触发了地图click事件!");
            console.log('carText模拟触发了地图click事件-e')
            const carInfo = e.target.lisaCarInfo
            const now_text = _this.createTextDome(carInfo)
            new AMap.InfoWindow({
              content: now_text
            }).open(mapObj, e.lnglat)
            // 向父级调用事件
            _this.$emit('car-click', now_item)
          }
          carText.on('click', clickHandler2)
          carText.setMap(mapObj)
        }
      },
      typeThreeFunc(data, zoom, queryType) {
        const _this = this
        console.log('typeThreeFunc()', data, 'zoom', zoom)
        const capitals = data
        const mapObj = new AMap.Map('mapAmap2', {
          // mapStyle: 'amap://styles/grey',
          center: new AMap.LngLat(capitals[0].longitude, capitals[0].latitude),
          zoom: zoom
        })
        mapObj.clearMap() // 清除地图覆盖物
        // ------2
        // 设置 marker-text 集合
        const setFitViewArr1 = createMarker(capitals)
        const setFitViewArr2 = createText(capitals)
        // console.log('setFitViewArr1', setFitViewArr1.length)
        mapObj.setFitView(setFitViewArr1.concat(setFitViewArr2)) // 调整视野达到最佳显示区域
        // 途径节点 marker 集合
        function createMarker(now_arr) {
          // 创建 red-icon
          const driverRedIcon = new AMap.Icon({
            size: new AMap.Size(40, 40),
            image: _this.imgUrl_car_red,
            imageSize: new AMap.Size(40, 40)
          })
          // 创建 green-icon
          const driverGreenIcon = new AMap.Icon({
            size: new AMap.Size(40, 40),
            image: _this.imgUrl_car_green,
            imageSize: new AMap.Size(40, 40)
          })
          // 创建 green-icon
          const driverYellowIcon = new AMap.Icon({
            size: new AMap.Size(40, 40),
            image: _this.imgUrl_car_yellow,
            imageSize: new AMap.Size(40, 40)
          })
          const middleMarkers = []
          for (let f = 0; f < now_arr.length; f++) {
            const item = now_arr[f]
            // driverIcon 类别
            let driverIcon = {}
            if (item.type === '20') {
              driverIcon = driverYellowIcon
            } else if (item.type === '10') {
              driverIcon = driverGreenIcon
            } else if (item.type === '30') {
              driverIcon = driverRedIcon
            } else {
              driverIcon = driverGreenIcon
            }
            // 创建 marker
            const carMarker = new AMap.Marker({
              position: new AMap.LngLat(item.longitude, item.latitude),
              icon: driverIcon,
              map: mapObj
            })
            // 给 Marker 带上自定义私货
            carMarker.lisaCarInfo = item
            const now_item = item
            now_item.queryType = queryType
            // 监听地图- Marker 的点击事件
            const clickHandler3 = function(e) {
              // log.success("carMarker模拟触发了地图click事件!");
              console.log('carMarker模拟触发了地图click事件-e')
              const carInfo = e.target.lisaCarInfo
              const now_text = _this.createTextDome(carInfo)
              new AMap.InfoWindow({
                content: now_text
              }).open(mapObj, e.lnglat)
              // 向父级调用事件
              _this.$emit('car-click', now_item)
            }
            carMarker.on('click', clickHandler3)
            carMarker.setTitle(item.plateLicenseNo) // 设置节点 名称
            carMarker.setMap(mapObj)
            middleMarkers.push(carMarker)
          }
          return middleMarkers
        }
        // 创建text标签 集合
        function createText(now_arr) {
          const middleTexts = []
          for (let f = 0; f < now_arr.length; f++) {
            const item = now_arr[f]
            // 创建 text
            const carText = new AMap.Text({
              position: new AMap.LngLat(item.longitude, item.latitude),
              offset: new AMap.Pixel(70, -8),
              text: item.plateLicenseNo,
              map: mapObj
            })
            // 给 Text 带上自定义私货
            carText.lisaCarInfo = item
            const now_item = item
            now_item.queryType = queryType
            // 监听地图- Text 的 点击事件
            const clickHandler4 = function(e) {
              // log.success("carText模拟触发了地图click事件!");
              console.log('carText模拟触发了地图click事件-e')
              const carInfo = e.target.lisaCarInfo
              const now_text = _this.createTextDome(carInfo)
              new AMap.InfoWindow({
                content: now_text
              }).open(mapObj, e.lnglat)
              // 向父级调用事件
              _this.$emit('car-click', now_item)
            }
            carText.on('click', clickHandler4)
            carText.setMap(mapObj)
            middleTexts.push(carText)
          }
          return middleTexts
        }
      },
      typeFourFunc(data, zoom, queryType) {
        const _this = this
        console.log('typeThreeFunc()', 'zoom', zoom)
        const capitals = data
        const mapObj = new AMap.Map('mapAmap2', {
          // mapStyle: 'amap://styles/grey',
          center: new AMap.LngLat(capitals[0].longitude, capitals[0].latitude),
          zoom: zoom
        })
        mapObj.clearMap() // 清除地图覆盖物
        // ------2
        // 设置 marker-text 集合
        const setFitViewArr1 = createMarker(capitals)
        console.log('setFitViewArr1', setFitViewArr1.length)
        mapObj.setFitView(setFitViewArr1) // 调整视野达到最佳显示区域
        // 途径节点 marker 集合
        function createMarker(now_arr) {
          // 创建 red-icon
          const driverRedIcon = new AMap.Icon({
            size: new AMap.Size(40, 40),
            image: _this.imgUrl_car_red,
            imageSize: new AMap.Size(40, 40)
          })
          // 创建 green-icon
          const driverGreenIcon = new AMap.Icon({
            size: new AMap.Size(40, 40),
            image: _this.imgUrl_car_green,
            imageSize: new AMap.Size(40, 40)
          })
          // 创建 green-icon
          const driverYellowIcon = new AMap.Icon({
            size: new AMap.Size(40, 40),
            image: _this.imgUrl_car_yellow,
            imageSize: new AMap.Size(40, 40)
          })
          const middleMarkers = []
          for (let f = 0; f < now_arr.length; f++) {
            const item = now_arr[f]
            // driverIcon 类别
            let driverIcon = {}
            if (item.type === '20') {
              driverIcon = driverYellowIcon
            } else if (item.type === '10') {
              driverIcon = driverGreenIcon
            } else if (item.type === '30') {
              driverIcon = driverRedIcon
            } else {
              driverIcon = driverGreenIcon
            }
            // 创建 marker
            const carMarker = new AMap.Marker({
              position: new AMap.LngLat(item.longitude, item.latitude),
              icon: driverIcon,
              map: mapObj
            })
            // 给 Marker 带上自定义私货
            carMarker.lisaCarInfo = item
            const now_item = item
            now_item.queryType = queryType
            // 监听地图- Marker 的点击事件
            const clickHandler3 = function(e) {
              // log.success("carMarker模拟触发了地图click事件!");
              console.log('carMarker模拟触发了地图click事件-e')
              // 向父级调用事件
              _this.$emit('car-click', now_item)
            }
            carMarker.on('click', clickHandler3)
            // setLabel
            const now_text = _this.createTextDome(item)
            carMarker.setLabel({
              offset: new AMap.Pixel(70, -8),  //设置文本标注偏移量
              content: now_text,
              direction: 'right' //设置文本标注方位
            })
            carMarker.setTitle(item.plateLicenseNo) // 设置节点 名称
            carMarker.setMap(mapObj)
            middleMarkers.push(carMarker)
          }
          return middleMarkers
        }
      },
      // createTextDome
      createTextDome(item) {
        // console.log('createTextDome()-', item)
        const _this = this
        let now_text = '<div>' + '车牌号:' + item.plateLicenseNo
        now_text += '</br>车架号:' + item.vin
        now_text += '</br>TBOX编号:' + _this.optionFilterFunc(item.tboxNo)
        now_text += '</br>上报时间:' + Utils.parseTime(item.acquisitionTime, '{y}-{m}-{d} {h}:{i}:{s}')
        now_text += '</br>当前位置:' + _this.optionFilterFunc(item.province) + _this.optionFilterFunc(item.city) + _this.optionFilterFunc(item.county)
        now_text += '</br>当前经纬度:' + item.longitude + ',' + item.latitude
        now_text += '</br>车辆状态:' + _this.vehicleTypeFilter(item.type)
        now_text += '</br>速度:' + _this.optionFilterFunc2(item.vehicleSpeed) + 'km/h'
        now_text += '</br>里程:' + _this.optionFilterFunc2(item.totalDistance) + 'km'
        now_text += '</br>电池剩余电量:' + _this.optionFilterFunc2(item.vehBatSoc) + '%' + '</div>'
        return now_text
      },
      // Filter
      vehicleTypeFilter(str) {
        const p_str = parseInt(str)
        if (p_str === 10) {
          return '运行'
        } else if (p_str === 20) {
          return '故障'
        } else if (p_str === 30) {
          return '风险'
        } else {
          return ''
        }
      },
      optionFilterFunc(val) {
        if (val) {
          return val
        } else {
          return ''
        }
      },
      optionFilterFunc2(val) {
        if (val) {
          return val
        } else {
          return 0
        }
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  #mapAmap2{
    margin: 0 0 0 0;
    width:100%;
    height:800px;
  }
</style>
